const utils = require("../utils/utils");
const config = require("../utils/config");

// 状态码
const codeObj = config.codeObj;

// 查询
exports.query = (req, res) => {
  console.log(req.body);
  console.log(req.query);
  // 返回数据结构
  let resObj = {
    code: codeObj.success,
  };
  // 执行查询
  let sql = "select * from test";
  console.log("测试SQL：", sql);
  req.db.driver.execQuery(sql, (err, data) => {
    if (err) {
      resObj.code = codeObj.fail;
      resObj.message = err.sqlMessage;
    } else {
      resObj.data = data;
    }
    res.json(resObj);
  });
};

// 增加
exports.add = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  let info = req.body;
  console.log(info);

  let sql = "insert into test(id, name, age) values(?, ?, ?)";
  console.log("SQL==========>：", sql);
  console.log("Params=======>：", info);

  let paramsValid = utils.paramsValid(info, ["name"]);
  if (paramsValid) {
    resObj.code = codeObj.fail;
    resObj.message = paramsValid + "参数不能为空";
    res.end(JSON.stringify(resObj));
    return;
  }
  req.db.driver.execQuery(
    sql,
    [utils.getUuid(), info.name, info.age],
    (err, data) => {
      if (err) {
        resObj.code = codeObj.fail;
        resObj.message = err.sqlMessage;
      } else {
        resObj.message = "添加成功";
      }
      res.json(resObj);
    }
  );
};

// 删除
exports.delete = (req, res) => {
  console.log(res.auth);
  let resObj = {
    code: codeObj.success,
  };
  let info = req.params;

  let sql = "delete from test where id=?";
  console.log("SQL==========>：", sql);
  console.log("Params=======>：", info);
  req.db.driver.execQuery(sql, [info.id], (err, data) => {
    if (err) {
      resObj.code = codeObj.fail;
      resObj.message = err.sqlMessage;
    } else {
      resObj.message = "删除成功";
    }
    res.json(resObj);
  });
};

// 表单
exports.formData = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  resObj.data = req.body;
  res.json(resObj);
};

// // 文件上传
// exports.uploadFile = (req, res) => {
//   res.redirect(308, "/api/uploadFile"); // 重定向
// };
exports.uploadFile = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  if (req.files) {
    if (req.files.length > 0) {
      let values = "";
      req.files.forEach((file) => {
        values += `('${utils.getUuid()}', '${file.originalname}', '${
          file.mimetype
        }', '${file.filename}'),`;
      });
      values = values.slice(0, -1);
      let sql =
        "insert into file(id, original_name, mimetype, filename) values" +
        values;
      req.db.driver.execQuery(sql, (err, data) => {
        if (err) {
          resObj.code = codeObj.fail;
          resObj.message = err.sqlMessage;
        } else {
          resObj.message = "添加成功";
        }
        return res.json(resObj);
      });
    } else {
      resObj.code = codeObj.fail;
      resObj.message = "文件上传失败";
      return res.json(resObj);
    }
  }
};

// 查看文件
exports.reviewFile = (req, res) => {};
